<template>
  <div class="user-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.keyword"
        placeholder="请输入用户名/手机号"
        clearable
        class="filter-item"
        style="width: 200px"
      />
      <el-button
        type="primary"
        :icon="Search"
        @click="handleQuery"
        class="filter-item"
      >
        搜索
      </el-button>
      <el-button
        type="success"
        :icon="Plus"
        @click="handleAdd"
        class="filter-item"
      >
        新增
      </el-button>
    </div>

    <el-table v-loading="loading" :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名"  />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="membershipNo" label="会员编号" />
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'success'">
            {{ scope.row.role === "ADMIN" ? "管理员" : "用户" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rechargeBalance" label="充值余额" width="100" />
      <el-table-column prop="giftBalance" label="赠送余额" width="100" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :icon="Edit"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.type === 'add'">
          <el-input
            v-model="userForm.password"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="会员编号" prop="membershipNo">
          <el-input
            v-model="userForm.membershipNo"
            placeholder="请输入会员编号"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="USER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="充值余额" prop="rechargeBalance">
          <el-input-number
            v-model="userForm.rechargeBalance"
            :min="0"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="赠送余额" prop="giftBalance">
          <el-input-number
            v-model="userForm.giftBalance"
            :min="0"
            :precision="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";
import { getUserList, saveUser, deleteUser } from "@/api/user";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
});

// 表格数据
const userList = ref([]);
const total = ref(0);
const loading = ref(false);

// 表单对话框
const dialog = reactive({
  visible: false,
  title: "",
  type: "", // add/edit
});

// 表单数据
const userFormRef = ref(null);
const userForm = reactive({
  id: undefined,
  username: "",
  password: "",
  name: "",
  phone: "",
  membershipNo: "",
  role: "USER",
  rechargeBalance: 0,
  giftBalance: 0,
});

// 表单验证规则
const userRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
};

// 生命周期钩子
onMounted(() => {
  getList();
});

// 获取用户列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getUserList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      keyword: queryParams.keyword,
    });

    if (res.code === 200 && res.data) {
      userList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表出错:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 分页操作
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getList();
};

const handleCurrentChange = (num) => {
  queryParams.pageNum = num;
  getList();
};

// 表单重置
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  userForm.id = undefined;
  userForm.username = "";
  userForm.password = "";
  userForm.name = "";
  userForm.phone = "";
  userForm.membershipNo = "";
  userForm.role = "USER";
  userForm.rechargeBalance = 0;
  userForm.giftBalance = 0;
};

// 新增按钮操作
const handleAdd = () => {
  resetForm();
  dialog.visible = true;
  dialog.title = "添加用户";
  dialog.type = "add";
};

// 编辑按钮操作
const handleEdit = (row) => {
  resetForm();
  dialog.visible = true;
  dialog.title = "编辑用户";
  dialog.type = "edit";
  Object.assign(userForm, row);
};

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用保存API
        const res = await saveUser(userForm);
        if (res.code === 200) {
          ElMessage.success(dialog.type === "add" ? "新增成功" : "修改成功");
          dialog.visible = false;
          getList(); // 刷新列表
        } else {
          ElMessage.error(res.msg || "操作失败");
        }
      } catch (error) {
        console.error("保存用户出错:", error);
        ElMessage.error("保存失败，请稍后重试");
      }
    }
  });
};

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除用户 ${row.name} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 调用删除API
        const res = await deleteUser(row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          getList(); // 刷新列表
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除用户出错:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .filter-container {
    margin-bottom: 20px;
    display: flex;
    align-items: center;

    .filter-item {
      margin-right: 10px;
    }
  }
}
</style>
